import { useState, useEffect } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import apiService from '../utils/api.js'
import { getGenderLabel, getTypeLabel, getNationalityLabel } from '../utils/constants.js'
import '../styles/pages.css'
import '../styles/artist-detail.css'

// 日期格式化函数
const formatDate = (dateString) => {
  try {
    const date = new Date(dateString)
    if (isNaN(date.getTime())) {
      return '未知日期'
    }
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    })
  } catch (error) {
    return '未知日期'
  }
}

function ArtistDetail({ playSong }) {
  const { id } = useParams() // 获取路由参数中的歌手ID
  const navigate = useNavigate()
  const [artist, setArtist] = useState(null)
  const [songs, setSongs] = useState([])
  const [albums, setAlbums] = useState([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')
  const [activeTab, setActiveTab] = useState('songs') // 新增：控制当前激活的标签页

  // 获取歌手详情
  const fetchArtistDetail = async () => {
    setLoading(true)
    setError('')
    try {
      // 调用API获取歌手详情
      const { statusCode, data } = await apiService.getArtistDetail(id)
      if (statusCode === 200) {
        const { albums= [], songs = [], ...artistInfo } = data
        setArtist(artistInfo)
        // 由于当前API只返回歌手基本信息，我们暂时使用模拟的歌曲和专辑数据
        // 在实际项目中，这里应该调用获取歌手歌曲和专辑的API
        setSongs(songs)
        setAlbums(albums)
      } else {
        throw new Error('歌手不存在')
      }
    } catch (err) {
      console.error('获取歌手详情失败:', err)
      setError(err.message || '获取歌手详情失败，请稍后再试')
    } finally {
      setLoading(false)
    }
  }

  // 生成模拟歌手详情数据
  const getMockArtistDetail = (artistId) => {
    // 基础歌手数据
    const artistBase = {
      id: parseInt(artistId),
      name: '',
      gender: 'male',
      type: 'pop',
      nationality: '华语歌手',
      avatarUrl: '',
      description: '',
      songs: [],
      albums: []
    }

    // 根据ID返回不同的歌手数据
    const artistDataMap = {
      1: {
        ...artistBase,
        name: '周杰伦',
        gender: 'male',
        type: 'pop',
        nationality: '华语歌手',
        avatarUrl: 'https://via.placeholder.com/400?text=周杰伦',
        description: '周杰伦（Jay Chou），1979年1月18日出生于台湾省新北市，祖籍福建省泉州市永春县，中国台湾流行乐男歌手、音乐人、演员、导演、编剧，毕业于淡江中学。2000年发行首张个人专辑《Jay》。2001年发行的专辑《范特西》奠定其融合中西方音乐的风格。2002年举行“The One”世界巡回演唱会。2003年成为美国《时代周刊》封面人物。',
        songs: [
          { id: 1, title: '晴天', album: '叶惠美', cover: 'https://via.placeholder.com/300', audio: '' },
          { id: 2, title: '七里香', album: '七里香', cover: 'https://via.placeholder.com/300', audio: '' },
          { id: 3, title: '青花瓷', album: '我很忙', cover: 'https://via.placeholder.com/300', audio: '' },
          { id: 4, title: '夜曲', album: '十一月的萧邦', cover: 'https://via.placeholder.com/300', audio: '' },
          { id: 5, title: '以父之名', album: '叶惠美', cover: 'https://via.placeholder.com/300', audio: '' }
        ],
        albums: [
          { id: 1, name: '叶惠美', releaseDate: '2003-07-31', cover: 'https://via.placeholder.com/300' },
          { id: 2, name: '七里香', releaseDate: '2004-08-03', cover: 'https://via.placeholder.com/300' },
          { id: 3, name: '我很忙', releaseDate: '2007-11-01', cover: 'https://via.placeholder.com/300' },
          { id: 4, name: '十一月的萧邦', releaseDate: '2005-11-01', cover: 'https://via.placeholder.com/300' },
          { id: 5, name: 'Jay', releaseDate: '2000-11-07', cover: 'https://via.placeholder.com/300' }
        ]
      },
      2: {
        ...artistBase,
        name: 'Taylor Swift',
        gender: 'female',
        type: 'pop',
        nationality: '欧美歌手',
        avatarUrl: 'https://via.placeholder.com/400?text=Taylor+Swift',
        description: '泰勒·斯威夫特（Taylor Swift），1989年12月13日出生于美国宾夕法尼亚州，美国女歌手、词曲作者、音乐制作人、演员。2006年，发行个人首张音乐专辑《Taylor Swift》，该专辑获得美国唱片业协会认证5倍白金唱片销量。',
        songs: [
          { id: 6, title: 'Blank Space', album: '1989', cover: 'https://via.placeholder.com/300', audio: '' },
          { id: 7, title: 'Shake It Off', album: '1989', cover: 'https://via.placeholder.com/300', audio: '' },
          { id: 8, title: 'Love Story', album: 'Fearless', cover: 'https://via.placeholder.com/300', audio: '' },
          { id: 9, title: 'All Too Well', album: 'Red', cover: 'https://via.placeholder.com/300', audio: '' },
          { id: 10, title: 'Anti-Hero', album: 'Midnights', cover: 'https://via.placeholder.com/300', audio: '' }
        ],
        albums: [
          { id: 6, name: '1989', releaseDate: '2014-10-27', cover: 'https://via.placeholder.com/300' },
          { id: 7, name: 'Fearless', releaseDate: '2008-11-11', cover: 'https://via.placeholder.com/300' },
          { id: 8, name: 'Red', releaseDate: '2012-10-22', cover: 'https://via.placeholder.com/300' },
          { id: 9, name: 'Midnights', releaseDate: '2022-10-21', cover: 'https://via.placeholder.com/300' },
          { id: 10, name: 'Lover', releaseDate: '2019-08-23', cover: 'https://via.placeholder.com/300' }
        ]
      },
      7: {
        ...artistBase,
        name: '五月天',
        gender: 'group',
        type: 'rock',
        nationality: '华语歌手',
        avatarUrl: 'https://via.placeholder.com/400?text=五月天',
        description: '五月天（Mayday），中国台湾摇滚乐团，由温尚翊（怪兽）、陈信宏（阿信）、石锦航（石头）、蔡升晏（玛莎）、刘谚明（冠佑）组成。1997年3月29日，五月天成立。1999年，发行组合首张音乐专辑《第一张创作专辑》。2001年，凭借音乐专辑《爱情万岁》获得台湾金曲奖最佳乐团奖。',
        songs: [
          { id: 11, title: '干杯', album: '第二人生', cover: 'https://via.placeholder.com/300', audio: '' },
          { id: 12, title: '突然好想你', album: '后青春期的诗', cover: 'https://via.placeholder.com/300', audio: '' },
          { id: 13, title: '温柔', album: '爱情万岁', cover: 'https://via.placeholder.com/300', audio: '' },
          { id: 14, title: '你不是真正的快乐', album: '后青春期的诗', cover: 'https://via.placeholder.com/300', audio: '' },
          { id: 15, title: '我不愿让你一个人', album: '第二人生', cover: 'https://via.placeholder.com/300', audio: '' }
        ],
        albums: [
          { id: 11, name: '第二人生', releaseDate: '2011-12-16', cover: 'https://via.placeholder.com/300' },
          { id: 12, name: '后青春期的诗', releaseDate: '2008-10-23', cover: 'https://via.placeholder.com/300' },
          { id: 13, name: '爱情万岁', releaseDate: '2000-07-07', cover: 'https://via.placeholder.com/300' },
          { id: 14, name: '自传', releaseDate: '2016-07-21', cover: 'https://via.placeholder.com/300' },
          { id: 15, name: '第一张创作专辑', releaseDate: '1999-07-07', cover: 'https://via.placeholder.com/300' }
        ]
      }
    }

    // 如果找不到对应的ID，返回一个默认的歌手数据
    return artistDataMap[artistId] || {
      ...artistBase,
      id: parseInt(artistId),
      name: `歌手${artistId}`,
      avatarUrl: `https://via.placeholder.com/400?text=歌手${artistId}`,
      description: '这是一位优秀的歌手',
      songs: [
        { id: 101, title: '歌曲1', album: '专辑1', cover: 'https://via.placeholder.com/300', audio: '' },
        { id: 102, title: '歌曲2', album: '专辑1', cover: 'https://via.placeholder.com/300', audio: '' }
      ],
      albums: [
        { id: 101, name: '专辑1', releaseDate: '2023-01-01', cover: 'https://via.placeholder.com/300' },
        { id: 102, name: '专辑2', releaseDate: '2022-01-01', cover: 'https://via.placeholder.com/300' }
      ]
    }
  }

  // 返回上一页
  const handleBack = () => {
    navigate(-1)
  }

  // 组件加载时获取数据
  useEffect(() => {
    fetchArtistDetail()
  }, [id])

  // 处理标签页切换
  const handleTabChange = (tab) => {
    setActiveTab(tab)
  }

  // 处理歌曲播放
  const handlePlaySong = (song) => {
    console.log('播放歌曲:', song)
    // 使用从父组件传递的playSong函数来实际播放歌曲
    if (playSong) {
      playSong(song)
    } else {
      alert(`正在播放: ${song.title}`)
    }
  }



  // 加载状态显示
  if (loading) {
    return (
      <div className="artist-detail-page loading-container">
        <div className="loading-spinner"></div>
        <p>加载中...</p>
      </div>
    )
  }

  // 错误状态显示
  if (error) {
    return (
      <div className="artist-detail-page error-container">
        <p>{error}</p>
        <button onClick={fetchArtistDetail}>重试</button>
      </div>
    )
  }

  return (
    <div className="artist-detail-page">
      {/* 返回按钮 */}
      <button className="back-button" onClick={handleBack}>
        ← 返回
      </button>

      {/* 歌手信息区域 */}
      <div className="artist-info-section">
        <div className="artist-avatar-large">
          <img 
            src={artist.avatarUrl} 
            alt={artist.name}
          />
        </div>
        <div className="artist-basic-info">
          <h1 className="artist-name-large">{artist.name}</h1>
          <div className="artist-meta-info">
            <span className="artist-gender">{getGenderLabel(artist.gender)}</span>
            <span className="artist-type">{getTypeLabel(artist.type)}</span>
            <span className="artist-nationality">{getNationalityLabel(artist.nationality)}</span>
          </div>
          <p className="artist-description">{artist.description}</p>
        </div>
      </div>

      {/* 内容切换标签 */}
      <div className="content-tabs">
        <button 
          className={`tab-button ${activeTab === 'songs' ? 'active' : ''}`}
          onClick={() => handleTabChange('songs')}
        >
          歌曲
        </button>
        <button 
          className={`tab-button ${activeTab === 'albums' ? 'active' : ''}`}
          onClick={() => handleTabChange('albums')}
        >
          专辑
        </button>
      </div>

      {/* 歌曲列表 */}
      {activeTab === 'songs' && (
        <div className="songs-section">
          <h2 className="section-title">歌曲 ({songs.length})</h2>
          <div className="songs-list">
            {songs.map((song, index) => (
              <div key={song.id} className="song-item">
                <div className="song-rank">{index + 1}</div>
                <div className="song-cover">
                  <img src={song.coverImageUrl} alt={song.title} />
                </div>
                <div className="song-info">
                  <div className="song-title">{song.title}</div>
                  <div className="song-album">{song.album?.name}</div>
                </div>
                <div className="song-actions">
                  <button className="play-btn" onClick={() => handlePlaySong(song)}>
                    播放
                  </button>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* 专辑列表 */}
      {activeTab === 'albums' && (
        <div className="albums-section">
          <h2 className="section-title">专辑 ({albums.length})</h2>
          <div className="albums-grid">
            {albums.map((album) => (
              <div 
                key={album.id} 
                className="album-card"
                onClick={() => navigate(`/album/${album.id}`)}
                style={{ cursor: 'pointer' }}
              >
                <div className="album-cover">
                  <img src={album.coverImageUrl} alt={album.title} />
                </div>
                <div className="album-info">
                  <div className="album-name">{album.title}</div>
                  <div className="album-date">{album.releaseDate ? formatDate(album.releaseDate) : '未知日期'}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  )
}

export default ArtistDetail